package com.atguigu.gmall.controller;

import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.model.product.SkuInfo;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class CartController {

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private CartFeignClient cartFeignClient;

    @RequestMapping("/cart.html")
    public String toCartPage() {
        return "cart/index.html";
    }

    @RequestMapping("/addCart.html")
    public String addCart(@RequestParam("skuId") Long skuId,
                          @RequestParam("skuNum") Integer skuNum,
                          Model model) {
        Result result = cartFeignClient.addToCart(skuId, skuNum);
        if (ResultCodeEnum.SUCCESS.getCode().equals(result.getCode())) {
            Result<SkuInfo> skuInfo = productFeignClient.getSkuInfo(skuId);
            SkuInfo skuInfoData = skuInfo.getData();
            model.addAttribute("skuInfo", skuInfoData);
        }else{
            model.addAttribute("code", result.getCode());
            model.addAttribute("message", result.getMessage());
            return "error/index.html";
        }
        return "cart/addCart.html";
    }
}
